﻿using HCMS.CommonDtos;
using HCMS.Entities.Manage;
using HCMS.Extensions;
using HCMS.IServices.Manage;
using Microsoft.AspNetCore.Mvc;

namespace HCMS.Web.Manage.Controllers.Module.Manage
{
    /// <summary>
    /// 管理 角色
    /// </summary>
    public class RoleController : ModuleController
    {
        private readonly IRoleAppService roleAppService;
        private readonly IRoleMenuAppService roleMenuAppService;

        public RoleController(
            IRoleAppService roleAppService,
            IRoleMenuAppService roleMenuAppService)
        {
            this.roleAppService = roleAppService;
            this.roleMenuAppService = roleMenuAppService;
        }

        #region 列表
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult List()
        {
            return View($"{BasePath}/Manage/Role/List.cshtml");
        }

        /// <summary>
        /// 列表 Ajax
        /// </summary>
        /// <remarks>
        /// 树结构 数据
        /// </remarks>
        /// <returns></returns>
        [ActionName("List")]
        [HttpPost]
        public async Task<IActionResult> PostList()
        {
            var searchArgs = new SearchArgsDto()
            {
                Status = Request.Form["status"].ToInt(9999),

                SearchName = Request.Form["searchName"].ToString(),
                SearchKey = Request.Form["searchKey"].ToString()
            };

            var pager = new PagerArgsDto()
            {
                IsPager = false
            };

            var result = await roleAppService.ManageList(searchArgs, pager);
            var isSearch = !string.IsNullOrWhiteSpace(searchArgs.SearchKey) && result.Data.Any();

            // 搜索，直接返回结果
            if (isSearch)
            {
                var obj = result.Data.ToList().Select(a => new
                {
                    id = a.Id,
                    name = a.Name,
                    status = a.Status,
                    createTime = a.CreateTime,
                    createUser = a.CreateUser,
                    updateTime = a.UpdateTime,
                    updateUser = a.UpdateUser
                }).ToList();
                return Json(new { code = 0, data = obj, count = result.PagerInfo.RowCount, msg = "ok" });
            }

            // 没有搜索，返回全部数据
            var allTree = await roleAppService.GetAllTree();

            return Json(new { code = 0, data = allTree, msg = "ok" });
        }
        #endregion

        #region 新增、编辑、保存
        /// <summary>
        /// 新增
        /// </summary>
        /// <returns></returns>
        public IActionResult Add()
        {
            var model = new Role();
            return View($"{BasePath}/Manage/Role/Edit.cshtml", model);
        }

        /// <summary>
        /// 添加子级
        /// </summary>
        /// <param name="parentId">父级 Id</param>
        /// <returns></returns>
        public IActionResult AddChildren(int parentId = 0)
        {
            var model = new Role()
            {
                ParentId = parentId
            };
            return View($"{BasePath}/Manage/Role/Edit.cshtml", model);
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Edit(int id)
        {
            if (id <= 0)
            {
                return Content("参数无效");
            }

            var model = await roleAppService.BaseFirstOrDefaultAsync(t => t.Id == id);
            if (model == null)
            {
                return Content($"没有找到【id：{id}】角色信息");
            }

            return View($"{BasePath}/Manage/Role/Edit.cshtml", model);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public async Task<IActionResult> Save(Role role)
        {
            Role? result = null;

            if (role == null)
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "参数异常" });
            }
            if (string.IsNullOrWhiteSpace(role.Name))
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "请填写名称" });
            }

            var parentId = Request.Form["ParentId"].ToInt(-1);
            if (parentId == -1)
            {
                throw new Exception("请选择所属上级");
            }

            var parentPath = (await roleAppService.BaseFirstOrDefaultAsync(t => t.Id == parentId))?.ParentPath;

            if (!string.IsNullOrWhiteSpace(parentPath))
            {
                var pathIdArray = parentPath.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var pathIdList = Array.ConvertAll(pathIdArray, int.Parse).ToList();
                pathIdList.Add(parentId);
                parentPath = string.Join(",", pathIdList);
            }
            else
            {
                parentPath = $"{parentId}";
            }

            var entity = await roleAppService.BaseFirstOrDefaultAsync(t => t.Id == role.Id);
            if (entity != null)
            {
                if (entity.Id == parentId)
                {
                    throw new Exception("不能选择自己作为上级，请重新选择");
                }

                entity.Name = role.Name;
                entity.ParentId = parentId;
                entity.ParentPath = parentPath;
                entity.Status = role.Status;
                entity.UpdateTime = DateTime.Now;
                entity.UpdateUser = CurrentAdmin.AdminName;
                result = await roleAppService.BaseUpdateAsync(entity);
            }
            else
            {
                entity = new Role()
                {
                    CreateTime = DateTime.Now,
                    CreateUser = CurrentAdmin.AdminName,
                    UpdateTime = DateTime.Now,
                    UpdateUser = CurrentAdmin.AdminName,
                    Name = role.Name,
                    ParentId = parentId,
                    ParentPath = parentPath,
                    Status = role.Status
                };
                result = await roleAppService.BaseInsertAsync(entity);
            }

            if (result != null)
            {
                return Json(new AjaxResultDto() { Message = "处理成功" });
            }
            else
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "处理失败" });
            }
        }
        #endregion

        #region 获取角色树结构
        /// <summary>
        /// 获取角色树结构
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> AllTree()
        {
            var result = await roleAppService.GetAllTree();
            return Json(result);
        }
        #endregion

        #region 设置角色权限
        /// <summary>
        /// 设置角色权限
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> SetRoleMenu(int roleId)
        {
            var roleName = string.Empty;
            var roleInfo = await roleAppService.BaseFirstOrDefaultAsync(t => t.Id == roleId);
            if (roleInfo != null)
            {
                roleName = roleInfo.Name;
            }

            var menuIds = string.Empty;
            var menuIdList = await roleMenuAppService.GetSelectMenuIdByRoleId(roleId);
            if (menuIdList != null && menuIdList.Count > 0)
            {
                menuIds = string.Join(",", menuIdList);
            }

            ViewData["roleName"] = roleName;
            ViewData["menuIds"] = menuIds;

            return View($"{BasePath}/Manage/Role/SetRoleMenu.cshtml");
        }

        /// <summary>
        /// 保存角色权限
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> SaveRoleMenu()
        {
            var roleId = Request.Form["roleId"].ToInt(0);
            var menuIds = Request.Form["menuIds"].ToString("");

            var menuIdList = new List<int>();
            if (!string.IsNullOrWhiteSpace(menuIds))
            {
                var menuIdArray = menuIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                menuIdList = Array.ConvertAll(menuIdArray, int.Parse).ToList();
            }

            var result = await roleMenuAppService.SetRoleMenu(roleId, menuIdList, CurrentAdmin.AdminName);
            if (result)
            {
                // 刷新缓存
                await roleMenuAppService.RefreshCacheByRoleId(roleId);

                return Json(new AjaxResultDto() { Message = "处理成功" });
            }
            else
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "处理失败" });
            }
        }
        #endregion

        #region 刷新角色权限缓存
        /// <summary>
        /// 刷新角色权限缓存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> RefreshRoleMenuCache()
        {
            int roleId = Request.Form["roleId"].ToInt(0);
            if (roleId <= 0)
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "角色参数无效" });
            }
            await roleMenuAppService.RefreshCacheByRoleId(roleId);

            return Json(new AjaxResultDto() { Message = "刷新成功" });
        }
        #endregion
    }
}
